package run.siyuan.rabbitmq.retry.message.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import run.siyuan.common.constant.rabbitmq.Constants;

import java.util.HashMap;
import java.util.Map;

//@ConditionalOnProperty(value = "youpik.rabbitmq.enable", havingValue = "true")
@Configuration
public class RetryRabbitConfig {

    /**
     * ------------------- 延时队列相关 -------------------
     * @return
     */

    /**
     * 延时交换机
     */
    @Bean
    public DirectExchange ttlDelayExchangeRetry() {
        return new DirectExchange(Constants.Queue.RABBITMQ_DELAY_EXCHANGE);
    }

    /**
     * 延时交换机队列
     */
    @Bean
    public Queue ttlDelayExchangeQueueRetry() {
        Map<String, Object> map = new HashMap<String, Object>();
        //队列中所有消息5秒后过期
        //map.put("x-message-ttl", 1000 * 60 * 5);
        //过期后进入死信队列
        map.put("x-dead-letter-exchange", Constants.Queue.RABBITMQ_DELAY_LETTER_EXCHANGE);
        return new Queue(Constants.Queue.RABBITMQ_DELAY_EXCHANGE_QUEUE, false, false, false, map);
    }

    /**
     * Fanout交换机和productQueue绑定
     */
    @Bean
    public Binding bindTtlExchangeAndQueueRetry() {
        return BindingBuilder.bind(ttlDelayExchangeQueueRetry()).to(ttlDelayExchangeRetry()).with(Constants.Queue.RABBITMQ_DELAY_EXCHANGE_ROUTE_KEY);
    }

    /**
     * ------------------- 死信队列相关 -------------------
     */

    /**
     * fanout死信交换机
     *
     * @return
     */
    @Bean
    public FanoutExchange deadLetterExchange() {
        return new FanoutExchange(Constants.Queue.RABBITMQ_DELAY_LETTER_EXCHANGE);
    }

    /**
     * 死信队列
     *
     * @return
     */
    @Bean
    public Queue deadLetterQueue() {
        return new Queue(Constants.Queue.RABBITMQ_DELAY_LETTER_EXCHANGE_QUEUE);
    }

    /**
     * 死信队列和死信交换机绑定
     *
     * @return
     */
    @Bean
    public Binding deadLetterBind() {
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange());
    }
}